package com.ilas.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.ilas.entity.TenantInfo;
import com.ilas.service.ITenantInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * 初始化动态数据源
 * @author Luzck
 * @date 2019/11/06
 */
@Slf4j
@Configuration
public class DynamicDataSourceInit {

    @Resource
    private ITenantInfoService tenantInfoService;

    @Resource
    private DynamicDataSource dynamicDataSource;


    @PostConstruct
    public void initDataSource() throws SQLException {
        log.info("=====初始化动态数据源=====");

        //加载master数据源除外的其他数据源
        List<TenantInfo> tenantList = tenantInfoService.findList();
        for (TenantInfo tenantInfo : tenantList) {
            log.info(tenantInfo.toString());
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(tenantInfo.getDataSourceDriver());
            dataSource.setUrl(tenantInfo.getDataSourceUrl());
            dataSource.setUsername(tenantInfo.getDataSourceUsername());
            dataSource.setPassword(tenantInfo.getDataSourcePassword());
            dataSource.init();
            dynamicDataSource.setDataSources(tenantInfo);
        }
    }

}
